<?php
// +-------------------------------------------------------------------
// | 
// +-------------------------------------------------------------------
// | Copyright (c) 2009-2016 All rights reserved.
// +-------------------------------------------------------------------
namespace Kcdns\Admin\Controller;
use Kcdns\Admin\Common\ModelCfg;
use Think\Controller;

/**
 * 后台控制器基类
 */
class AdminController extends Controller
{

    public $breadcrumb = '';
    
    // 后台控制器初始化
    protected function _initialize ()
    {
        // 加载数据库配置项
        $config = S('DB_CONFIG_CACHE');
        if (! $config)
        {
            $configData = M('config')->where([
                'status' => 1
            ])->select() ?  : [];
            foreach ($configData as $v)
            {
                $config[$v['name']] = kcone_think_decrypt($v['value']);
            }
            S('DB_CONFIG_CACHE', $config);
        }
        C($config);

        // PJAX
        define('IS_PJAX', isset($_SERVER['HTTP_X_PJAX']));
        define('PJAX_CONTAINER', $_SERVER['HTTP_X_PJAX_CONTAINER']);
        
        // 当前用户
        define('UID', is_login());
        ! UID and IS_PJAX ? $this->error("请登录", U('Public/login')) : $this->redirect('Public/login');
        
        // 超级管理员
        define('IS_ROOT', is_administrator() && DEBUG_ROOT_ENABLE);
        
        // 检查用户是否禁用
        $user = M('member')->field('uid,status')->find(UID);
        if (! $user || $user['status'] <= 0)
        {
            D('Member')->logout();
            session('[destroy]');
            $this->error("请登录", U('Public/login'));
        }
        
        // 文件上传入口, 不检查权限
        if (! IS_ROOT && CONTROLLER_NAME != 'File')
        {
            // 检查功能权限
            checkRule(strtolower(MODULE_NAME . '/' . CONTROLLER_NAME . '/' . ACTION_NAME)) or $this->error('未授权访问!', U('Public/login'));
            
            // 检查数据权限
            $this->checkDynamic() === false and $this->error('未授权访问!', U('Public/login'));
        }
        
        if (! IS_AJAX)
        {
            $this->breadcrumb = getBreadCrumb();
            $this->meta_title = $this->breadcrumb[1]['title'] ?  : $this->breadcrumb[0]['title'];
            $this->assign('__MENU__', getMenus());
            $this->assign('html_title', $this->meta_title);
        }
        
        $this->assign('__CTL__', $this);
        
        ModelCfg::clearGP();
    }
    
    // 检测动态权限
    protected function checkDynamic ()
    {
        return true;
    }
    
    // 提示成功消息后退出
    protected function success ($message = '', $jumpUrl = '', $ajax = false)
    {
        exit(parent::success($message, $jumpUrl, $ajax));
    }
    
    // 方法不存在时尝试通过配置模型显示页面
    protected function _empty ()
    {
        // 优先使用 cfgx
        try
        {
            new ModelCfg();
        }
        catch (\Exception $e)
        {
            $this->display('Public/empty');
        }
        
        return A('Common')->{ACTION_NAME}();
    }
}